<?php

namespace app\oauth\controller;

use app\BaseController;
use app\oauth\logic\OauthLogic;
use app\oauth\service\AuthService;
use app\oauth\service\ValidateService;
use think\Request;

class Oauth extends BaseController
{
    /**
     * 登录
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     */
    public function login(Request $request)
    {
        ValidateService::check('Oauth','login',$request->param());

        $Oauth = new OauthLogic();
        $token = $Oauth->login($request->param());
        if (!$token) {
            return JsonData(1001, "密码错误");
        }

        return JsonData(SUCCESS_CODE, "登录成功", ['token' => $token]);
    }

    /**
     * 项目是否安装
     * @return \think\response\Json
     */
    public function installed()
    {
        $Oauth = new OauthLogic();
        if ($Oauth->getLock()) {
            return JsonData(SUCCESS_CODE, "已安装");
        }

        return JsonData(1001, "未安装");
    }

    /**
     * @return \think\response\Json
     * @throws \app\oauth\service\ExceptionService
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function register()
    {
        $Oauth = new OauthLogic();

        $data = $Oauth->register();
        if (!$data) {
            return JsonData(1001, "超级管理员初始化失败");
        }

        return JsonData(SUCCESS_CODE, "超级管理员初始化成功", $data);
    }

    public function changePassword(Request $request)
    {
        ValidateService::check('Oauth','change_password',$request->param());

        $Oauth = new OauthLogic();

        if ($Oauth->changePassword($request->param())) {
            return JsonData(SUCCESS_CODE, "管理员修改密码成功");
        }

        return JsonData(1001, "管理员修改密码失败");
    }

    /**
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function logout()
    {
        $Oauth = new OauthLogic();

        $return = $Oauth->logout(AuthService::userId());

        if (!$return) {
            return JsonData(1001, "失败");
        }

        return JsonData(SUCCESS_CODE, "成功");
    }
}
